#include <iostream>

using namespace std;


/**
 * Definition for a binary tree node.
 */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};


/**
 * @brief 打家劫舍 III
 * https://leetcode.cn/problems/house-robber-iii/
 */
class Solution {
public:
    /**
     * Rob(root) = val(root) + NotRob(root->left) + NotRob(root->right)
     * NotRob(root) = max(NotRob(root->left), Rob(root->left)) + 
     *                max(NotRob(root->right), Rob(root->right))
     */
    int rob(TreeNode* root) {
        auto res = rob_helper(root);
        return max(get<0>(res), get<1>(res));
    }

    pair<int, int> rob_helper(TreeNode* root) {
        if (!root) return {0, 0};

        auto left = rob_helper(root->left);
        auto right = rob_helper(root->right);
        int rob = root->val + get<1>(left) + get<1>(right);
        int not_rob = max(get<1>(left), get<0>(left)) + max(get<1>(right), get<0>(right));

        return {rob, not_rob};
    }
};
